package com.zhang.mqtt.config;

import com.zhang.mqtt.handler.ReceiveMessageHandler;
import com.zhang.mqtt.properties.MqttProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @Author 超chao
 * @Description mqtt订阅配置 接受消息
 * @Date 2025/7/24/周四 13:34
 * @Version 1.0
 */
@Configuration
public class MqttInboundConfiguration {
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
    @Autowired
    private MqttProperties mqttProperties;
    @Autowired
    private ReceiveMessageHandler receiveMessageHandler;

    // 消息通道
    @Bean
    public MessageChannel messageInboundChannel(){
        return new DirectChannel();
    }

    // 配置入栈适配器，作用，设置订阅主题以及指定消息的相关属性
    @Bean
    public MessageProducer messageProducer(){

        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttProperties.getBroker(),
                mqttProperties.getSubClientId(),
                mqttPahoClientFactory,
                mqttProperties.getSubTopic().split(",")
        );

        adapter.setQos(1);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setOutputChannel(messageInboundChannel());
        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "messageInboundChannel")
    public MessageHandler messageHandler(){
        return receiveMessageHandler;
    }

}
